package top.kaoshanji.p3ch12a;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

/**
 * 代码清单-p3ch12a-225页a：登录的用户才能下载文件
 * URL访问地址：/download
 * @author kaoshanji
 * ^_^
 * create time 2025/4/9 9:57
 */
@WebServlet(urlPatterns = {"/download"})
public class FileDownloadServlet extends HttpServlet {

    private static final long serialVersionUID = 7583L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        // 没有登录，就要去登录页面
        if (session == null || session.getAttribute(Constant.HTTPSESSION_ATTRIBUTE_LOGGED) == null) {
            RequestDispatcher dispatcher = req.getRequestDispatcher(Constant.JSP_LOGIN);
            dispatcher.forward(req, resp);
            return; // forward方法不会代码执行，所以如果下面还有代码就需要返回
        }

        // 本地文件
        String fileName = "secret.pdf";
        File file = new File(Constant.LOCAL_ROOT_PATH, fileName);

        if (file.exists()) { // 如果文件存在
            // 设置响应对象的编码和内容格式
            resp.setContentType("application/pdf"); // 响应内容是文件类型
            resp.addHeader("Content-Disposition", "attachment; filename=" + fileName); // 文件下载对话框中显示出来的默认文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                OutputStream os = resp.getOutputStream();
                int i = bis.read(buffer); // 读到缓冲区
                while (i != -1) {
                    os.write(buffer, 0, i); // 通过缓冲区写
                    i = bis.read(buffer);
                }
            } catch (IOException e) {
                System.out.println(e.toString());
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
        }
    }

}
